package com.je.paas.document.controller;

import cn.hutool.core.io.IoUtil;
import com.je.core.exception.PlatformException;
import com.je.core.exception.PlatformExceptionEnum;
import com.je.core.result.BaseRespResult;
import com.je.core.service.MetaService;
import com.je.core.util.DateUtils;
import com.je.core.util.JEUUID;
import com.je.core.util.SecurityUserHolder;
import com.je.core.util.bean.DynaBean;
import com.je.paas.document.model.bo.FileBO;
import com.je.paas.document.service.DocumentBusService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @program: je-platform
 * @author: LIULJ
 * @create: 2020-03-16 18:39
 * @description:
 */
@Controller("documentShareControl")
@RequestMapping(value = "/je/docShare")
public class DocumentShareController {

    @Autowired
    private DocumentBusService documentBusService;
    @Autowired
    private MetaService metaService;

    /**
     * 获取文档分享地址
     *
     * @param fileKey
     * @return
     * @author huxuanhua
     */
    @RequestMapping(value = "/getShare", produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getShareUrl(String fileKey) {
        //用户ID
        String userId = SecurityUserHolder.getCurrentUser().getUserId();
        if (StringUtils.isEmpty(fileKey)) {
            return BaseRespResult.errorResult("filekey不能为空");
        }
        try {
            String id = JEUUID.uuid();
            String share_url = "/je/docShare/share?share_id=" + id;
            DynaBean dynaBean = new DynaBean("JE_DOCUMENT_SHARE", false);
            dynaBean.set("JE_DOCUMENT_SHARE_ID", id);
            dynaBean.set("SHARE_WDID", fileKey);
            dynaBean.set("SHARE_FXR", userId);
            dynaBean.set("SHARE_FXSJ", DateUtils.formatDateTime(new Date()));
            dynaBean.set("SHARE_FXURL", share_url);
            metaService.insert(dynaBean);
            return BaseRespResult.successResult(share_url);
        } catch (Exception e) {
            throw new PlatformException("生成分享链接报错=", PlatformExceptionEnum.UNKOWN_ERROR, e);
        }
    }

    /**
     * 获取文档分享地址
     * @param share_id
     * @return
     * @author huxuanhua
     */
    @RequestMapping(value = "/share", produces = "application/json; charset=utf-8")
    @ResponseBody
    public void shareAddress(HttpServletRequest request, HttpServletResponse response, String share_id) {
        String fileKey = null;
        try {
            DynaBean dynaBean = metaService.selectOneByPk("JE_DOCUMENT_SHARE", share_id);
            fileKey = dynaBean.getStr("SHARE_WDID");
            response.reset();
            //获取文件信息
            FileBO fileBO = null;
            fileBO = documentBusService.readFile(fileKey);
            String fileName = URLEncoder.encode(fileBO.getRelName(), "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            InputStream is = fileBO.getFile();
            if (is == null) {
                throw new PlatformException(String.format("文件[%s]查找错误", fileKey), PlatformExceptionEnum.UNKOWN_ERROR, request);
            }
            //写入文件流
            response.setContentType(fileBO.getContentType());
            OutputStream toClient = response.getOutputStream();
            IoUtil.copy(fileBO.getFile(), toClient);
            IoUtil.close(fileBO.getFile());
            toClient.flush();
            toClient.close();
        } catch (PlatformException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlatformException(String.format("文件[%s]查找错误", fileKey), PlatformExceptionEnum.UNKOWN_ERROR, request);
        }


    }

}
